//
//  NetworkTool.swift
//  YouYouDriver
//
//  Created by Apple on 2017/8/28.
//  Copyright © 2017年 The_X. All rights reserved.
//

import Foundation
import Alamofire
import SVProgressHUD

@objc enum NetMethod: Int {
    
    case GET
    case POST
}


class NetworkTool: NSObject {

    static let shared = NetworkTool()
    
    private override init() {
        
    }
    
    /// 令牌请求 (自动拼接令牌)
    
    class func tokenRequest(isShow: Bool = true,
                            method: NetMethod = .POST,
                            url: String,
                            parameter: [String: AnyObject]? = nil ,
                            finished: @escaping (_ result: [String: AnyObject]?, _ issuccess: Bool, _ msg: String?) -> ()) {
        
//        guard let token = UserModel.shared.token else {
//
//            return
//        }
        
        var para = parameter
        
        if para == nil {
            
            para = [String : AnyObject]()
        }
        
//        para!["uid"] =  UserModel.shared.id as AnyObject
//        para!["token"] = token as AnyObject
        
        isShow ? SVProgressHUD.show() : ()
        
        let httpMethod: HTTPMethod = method == .GET ? .get : .post
        
        Alamofire.request(url, method: httpMethod, parameters: para).responseJSON { (response) in
            
            SVProgressHUD.dismiss()
            
            switch response.result {
            case .success(let data):
                
                if let data = data as? [String: AnyObject],
                    let status = data["status"] as? Int{
                    
                    if status == 200 {
                        
                        finished(data, true, nil)
                        
                    } else if status == 16 {
                        
//                        UserDefaults.standard.removeObject(forKey: kUserId)
//                        UserDefaults.standard.removeObject(forKey: kToken)
//                        UserDefaults.standard.synchronize()
                        
                        keyWindow?.rootViewController = BaseNavigationController(rootViewController: LoginController())
                        
                        finished(nil, false, data["error_desc"] as? String)
                        
                    } else {
                        
                        finished(nil, false, data["error_desc"] as? String)
                    }
                }
                
            case .failure(let error):
                
                print(error)
                finished(nil, false, "网络请求超时")
            }
        }
    }
    
    /// 基础请求
    
    class func request(isShow: Bool = true,
                       method: NetMethod = .POST,
                       url: String, parameter: [String: AnyObject]? = nil,
                       finished: @escaping (_ result: [String: AnyObject]?, _ issuccess: Bool, _ msg: String?) -> ()) {
        
        isShow ? SVProgressHUD.show() : ()
        
        let httpMethod: HTTPMethod = method == .GET ? .get : .post
        
        Alamofire.request(url, method: httpMethod, parameters: parameter).responseJSON { (response) in
            
            SVProgressHUD.dismiss()
            
            switch response.result {
            case .success(let data):
                
                if let data = data as? [String: AnyObject],
                    let status = data["status"] as? Int{
                    
                    if status == 200 {
                        
                        finished(data, true, nil)
                        
                    } else {
                        
                        finished(nil, false, data["error_desc"] as? String)
                    }
                }
                
            case .failure(let error):
                
                print(error)
                finished(nil, false, "网络请求超时")
            }
        }
    }

    /// 多图上传
    
    class func upload(isShow: Bool = false,
                      url: String,
                      parameter: [String: String]?,
                      imageData: [String : Data],
                      finished: @escaping (_ result: [String: AnyObject]?, _ issuccess: Bool, _ msg: String?) -> ()) {
        
        isShow ? SVProgressHUD.show() : ()
        
        var para = parameter
        
        if para == nil {
            
            para = [String : String]()
        }
        
//        para!["uid"] =  "\(UserModel.shared.id)"
//        para!["token"] = UserModel.shared.token
        
        Alamofire.upload(multipartFormData: { (formData) in
            
            for (key, data) in imageData {
                
                formData.append(data, withName: key, fileName: "\(key).jpeg", mimeType: "image/jpeg")
            }
            
            for (key, value) in para! {
                
                formData.append(value.data(using: .utf8)!, withName: key)
            }
            
        }, to: url) { (result) in
            
            switch result {
            case .success(let upload, _,  _):
                
                upload.responseJSON { (response) in
                    
                    SVProgressHUD.dismiss()
                    
                    switch response.result {
                    case .success(let data):

                        if let data = data as? [String: AnyObject],
                            let status = data["status"] as? Int{
                            
                            if status == 200 {
                                
                                finished(data, true, nil)
                                
                            } else {
                                
                                finished(nil, false, data["error_desc"] as? String)
                            }
                        }
                    case .failure(let error):
                        
                        print(error)
                        finished(nil, false, "网络请求超时")
                    }
                }
            case .failure(let error):
                
                print(error)
                finished(nil, false, "网络请求超时")
            }
        }
    }
}
